<?php

App::uses('AppController', 'Controller');

class ImagesController extends AppController {
    
    public $uses = array('Member', 'MemberImage', 'OrganisationMember','OrganisationMemberImage');
    
    public function manager() {
        $this->autoLayout = false;
        
        // get org information
        $orgAccount = $this->Session->read('org_account');
        
        $untagged = $this->MemberImage->getUntagged( $orgAccount['Organisation']['id'] );
        
        $this->set(compact('untagged'));
    }
    
    /**
     * Uploads a file and saves the binary data to the database. A new record
     * will be created for the image data, or a record will be updated if a record
     * ID is specified as the parameter.
     * 
     * The method will return an instance of the GameGraphic object if the $save_game_graphic
     * parameter is set to true. If false, the image data would simply returned so it can be
     * used in another process if required
     * 
     * @param int $game_graphic_id
     * @param bool $save_game_graphic set to true to save game graphic, false to return graphic data
     * 
     * @return json
     */
    function upload() {

        $this->autoRender = false;
        $this->autoLayout = false;

        $fileType = $_FILES['uploadfile']['type'];

        # list of permitted file types, this is only images but documents can be added
        $permitted = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/svg+xml');

        $typeOk = false; # with the correct type the file will be uploaded or rejected.

        foreach ($permitted as $type) {
            if ($type == $fileType) {
                $typeOk = true;
                break;
            }
        }
        # if typeOk upload the file
        if ($typeOk) {

            // get the file data
            $file_contents = file_get_contents($_FILES['uploadfile']['tmp_name']);
            
            // get org information
            $orgAccount = $this->Session->read('org_account');
            
            // generate the file name for the name file
            $file_dir = WWW_ROOT . 'files/org_images/org_' . $orgAccount['Organisation']['id'] . "/";
            $file_path = $file_dir . "img_" . date("YmdHis") . ".jpg";
            
            $file_url = "/files/org_images/org_" . $orgAccount['Organisation']['id'] . "/" . "img_" . date("YmdHis") . ".jpg";
            
            // create the directory and move the uploaded files
            if( !file_exists($file_dir) ) {
                mkdir($file_dir, 0777, true);
            }
            
            move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file_path);
            
            // save the graphic information to the database, by updating or inserting a new record
            $this->MemberImage->set(array(
                'file_path' => $file_url
            ));
            
            if( isset($_POST['member_id']) ) {
                $this->MemberImage->set('member_id', $_POST['member_id']);
            }

            $data = $this->MemberImage->save();
            $data['MemberImage']['id'] = $this->MemberImage->id;
            $data['MemberImage']['file_url'] = Router::url($data['MemberImage']['file_path']);
                       
            if( isset($_POST['member_id']) ) {
                $orgAccount = $this->Session->read('org_account');
                
                $this->MemberImage->assign($this->MemberImage->id, $orgAccount['Organisation']['id'], $_POST['member_id']);
            }

            return json_encode(array('status' => 'success', 'image' => $data));
        }

        return false;
    }
    
    public function tag_list() {
        $this->autoRender = false;
        
        $orgAccount = $this->Session->read('org_account');
        
        $members = $this->Api->post('/organisation/find_member', array(
            'organisation_id' => $orgAccount['Organisation']['id'],
            'organisation_member_category_id' => -1, // all members
            'term' => $_GET['term'],
            'limit' => 10,
            'order' => array('Member.last_name' => 'asc')
        ));
        
        $response = array();
        foreach($members as $member) {
            $fullname = $member['Member']['last_name'] . ' ' . $member['Member']['first_name'];
            $label = "<span class='m_num'>{$member['OrganisationMember']['organisation_no']}</span> " . $fullname;
            $response[] = array('label' => $label, 'value' => array('id' => $member['Member']['id'], 'name' => $fullname, 'org_mem_id'=>$member['OrganisationMember']['id']) );
        }
        
        echo json_encode($response);
    }


    public function multi_tag() {
        $this->autoRender = false;

        $orgAccount = $this->Session->read('org_account');

        $tags = $_POST['tags'];

        if( empty($tags) ) {
            echo json_encode(array('status' => 'failed', 'message' => 'No Images Or Member Information To Complete Tagging'));
            return;
        }

        foreach($tags as $key => $value) {
            $this->MemberImage->set(array(
                'id' => $key,
                'member_id' => $value
            ));

            $this->MemberImage->save();

            $this->OrganisationMember->updateAll(
                array('member_image_id' => $key),
                array(
                    'member_id' => $value,
                    'organisation_id' => $orgAccount['Organisation']['id']
                )
            );
        }

        echo json_encode(array('status' => 'success', 'message' => 'tagging complete'));
    }


    public function tag() {
        $this->autoRender = false;
        $org_id = $this->getOrgData('id');
        $member_id = isset($_POST['member_id']) ? $_POST['member_id']: '';
        $member_image_id = $_POST['member_image_id'] ? $_POST['member_image_id']: '';
        $org_mem_image_id = $_POST['org_mem_image_id'] ? $_POST['org_mem_image_id']: '';
        $org_mem_id = $_POST['org_mem_id'] ? $_POST['org_mem_id']: '';

        if( empty($member_id) ||  empty($member_image_id) || empty($org_mem_image_id) || empty($org_mem_id)) {
            echo json_encode(array('status' => 'failed', 'message' => 'No Images Or Member Information To Complete Tagging'));
            return;
        }

        $this->MemberImage->set(array(
            'id' => $member_image_id,
            'member_id' => $member_id
        ));
        $res = $this->MemberImage->save();
        if($res){
            $this->OrganisationMemberImage->updateAll(
                array('organisation_member_id' => $org_mem_id),
                array(
                    'OrganisationMemberImage.id' => $org_mem_image_id,
                )
            );
            echo json_encode(array('status' => 'success', 'message' => 'Tagging complete'));
            return;
        }
        else{
            echo json_encode(array('status' => 'failed', 'message' => 'Cannot tag member to this image.'));
            return;
        }
    }
    
    public function untag() {
        $this->autoRender = false;
        if( isset($_POST['organisation_member_image_id']) ) {
            $res = $this->OrganisationMemberImage->updateAll(
                array('organisation_member_id' => null),
                array(
                    'OrganisationMemberImage.id' => $_POST['organisation_member_image_id'],
                )
            );
            if($res){
                return json_encode(array('status' => 'success', 'message' => 'Image Untagged Successfully') );
            }
            else{
                return json_encode(array('status' => 'failed', 'message' => 'Selected Image(s) Deletion Failed') );
            }
        }
        return json_encode(array('status' => 'failed', 'message' => 'Please Select One Image or More'));
    }


    public function delete_images() {
        $this->autoRender = false;

        if( isset($_POST['organisation_member_image_id']) ) {
            $res = $this->OrganisationMemberImage->delete_images($_POST['organisation_member_image_id']);
            if($res){
                return json_encode(array('status' => 'success', 'message' => 'Selected Image(s) Deleted Successfully') );
            }
            else{
                return json_encode(array('status' => 'failed', 'message' => 'Selected Image(s) Deletion Failed') );
            }
        }
        return json_encode(array('status' => 'failed', 'message' => 'Please Select One Image or More'));
    }


    public function load_member_images($page = 0) {
        $this->autoRender = false;
        $org_id = $this->getOrgData('id');

        $limit = 18; //how many items to show per page
        $adjacents = 3; // How many adjacent pages should be shown on each side?
        $filter = isset($_POST['filter']) ? $_POST['filter'] : 'untagged';
        $search = isset($_POST['search']) ? $_POST['search'] : false;
        
        if( $filter == "tagged" ) {
            $limit = 20;
        }

        $total_pages = $this->OrganisationMemberImage->count_member_images($org_id,$filter,$search);

        if($page) {
            $start = ($page - 1) * $limit; 			//first item to display on this page
        } else {
            $start = 0;
        }
        
        $images = $this->OrganisationMemberImage->load_member_images($org_id,$filter,$search,$start,$limit);

        /*foreach($images as $key => $image){
            $images[$key]['MemberImage']['url'] = $this->Upload->construct_file_url($image['MemberImage']['file_path'],$image['MemberImage']['file_name']);
        }*/

        $this->autoLayout = false;
        $view = new View($this, false);
        $view->set(compact('images','target_page','total_pages','limit','page','adjacents', 'filter')); // set variables
        $view->viewPath = 'Elements/organisation/admin/'; // render an element
        $html = $view->render('render_image'); // get the rendered markup

        $caps = ucfirst($filter);
        if($images){
            echo json_encode(array('status' => 'success', 'message' => $caps.' Images found','data'=>$images, 'render'=>$html));
        }
        else{
            echo json_encode(array('status' => 'failed', 'message' => $caps.' Images not found'));
        }
    }


    public function bulk_image_uploads(){
        $this->autoRender = false;

        $upload_data = $this->Upload->__attach_files();

        //Save the uploaded_data record if u want to //
        foreach($upload_data['files'] as $key => $file){
            if(isset($file['error'])){

            }
            else{
                $this->MemberImage->create();
                $res = $this->MemberImage->save(array(
                    'file_name'=>$file['name'],
                    'file_path'=>$file['save_to'],
                    'thumb_path'=>$file['save_to_thumb']
                ));
                if(isset($res['MemberImage'])){
                    $org_id = $this->getOrgData('id');
                    $this->OrganisationMemberImage->save(array(
                        'organisation_id'=>$org_id,
                        'member_image_id'=>$this->MemberImage->id
                    ));
                    $upload_data['files'][$key]['id']= $this->MemberImage->id;
                }
                else{
                    $upload_data['files'][$key]['error']= 'Uploaded but could not save file info to db';
                }
            }
        }

        $this->Upload->attachment_fire_response($upload_data);
    }


    public function upload_image_and_tag(){
        $this->autoRender = false;
        $member_id = isset($_POST['member_id']) ? $_POST['member_id']: '';
        $org_mem_id = isset($_POST['org_mem_id']) ? $_POST['org_mem_id']: '';

        if( empty($member_id) || empty($org_mem_id)) {
            echo json_encode(array('status' => 'failed', 'message' => 'No Images Or Member Information To Complete Upload'));
            return;
        }

        $upload_data = $this->Upload->__attach_files();
        //Save the uploaded_data record if u want to //
        foreach($upload_data['files'] as $key => $file){
            if(isset($file['error'])){

            }
            else{
                $this->MemberImage->create();
                $res = $this->MemberImage->save(array(
                    'file_name'=>$file['name'],
                    'file_path'=>$file['save_to'],
                    'thumb_path'=>$file['save_to_thumb'],
                    'member_id' => $member_id
                ));
                if(isset($res['MemberImage'])){
                    $org_id = $this->getOrgData('id');
                    $this->OrganisationMemberImage->save(array(
                        'organisation_id'=>$org_id,
                        'member_image_id'=>$this->MemberImage->id,
                        'organisation_member_id' => $org_mem_id
                    ));
                    $upload_data['files'][$key]['id']= $this->MemberImage->id;
                }
                else{
                    $upload_data['files'][$key]['error']= 'Uploaded but could not save file info to db';
                }
            }
        }

        $this->Upload->attachment_fire_response($upload_data);
    }
    
    public function import() {
        $this->autoRender = false;
        
        $MemberImage = ClassRegistry::init('MemberImage');
        
        $members = ClassRegistry::init('MMember')->find('all', array(
            'offset' => 50,
            'limit' => 50,
            'order' => array('id' => 'desc'),
            'recursive' => -1
        ));
        
        foreach($members as $member) {
            $image_dir = ROOT . "/../memberz_files/img/org_44/";
            $filename = $member['MMember']['FIRST_NAME'] . "_" . $member['MMember']['LAST_NAME'] . ".png";
            
            if( !file_exists($image_dir) ) {
                mkdir($image_dir, 0777);
            }
            debug(strlen($member['MMember']['IMAGE']));
            
            if( strlen($member['MMember']['IMAGE']) > 100 ) {
                $bytes = file_put_contents($image_dir . $filename, $member['MMember']['IMAGE']);

                $MemberImage->create();
                
                $data = $MemberImage->save(array(
                    'MemberImage' => array(
                        'member_id' => $member['MMember']['ID'],
                        'file_path' => '/img/org_44/' . $filename,
                        'thumb_path' => '/img/org_44/' . $filename,
                        'active' => 1
                    )
                ));

                $om = ClassRegistry::init('OrganisationMember')->find('first', array(
                    'conditions' => array(
                        'OrganisationMember.organisation_id' => 44,
                        'OrganisationMember.member_id' => $member['MMember']['ID']
                    )
                ));

                if( $om ) {
                    ClassRegistry::init('OrganisationMemberImage')->saveAll(array(
                        'OrganisationMemberImage' => array(
                            'organisation_id' => 44,
                            'organisation_member_id' => $om['OrganisationMember']['id'],
                            'member_image_id' => $MemberImage->id
                        )
                    ));
                }
            }
        }
    }

    public function upload_org_logo(){
        $this->autoRender = false;

        $orgAccount = $this->Session->read('org_account');

        $upload_data = $this->Upload->__attach_files();
        
        //Save the uploaded_data record if u want to //
        foreach($upload_data['files'] as $file){
            
            if( !isset($file['error']) ) {    
                $this->Organisation->save(array(
                    'id' => $orgAccount['Organisation']['id'],
                    'logo' => $file['url']
                ));
                
                $orgAccount['Organisation']['logo'] = $file['url'];
                
                $this->Session->write('org_account', $orgAccount);
            }
        }

        $this->Upload->attachment_fire_response($upload_data);
    }
}